/**
 *     {"total":4,"rows":[
    {"name":"Name","value":"Bill Smith","group":"ID Settings","editor":"text"},
    {"name":"Address","value":"","group":"ID Settings","editor":"text"},
    {"name":"SSN","value":"123-456-7890","group":"ID Settings","editor":"text"},
    {"name":"Email","value":"bill@gmail.com","group":"Marketing Settings","editor":{
    "type":"validatebox",
    "options":{
    "validType":"email"
    }
    }}
    ]}
 */
var userinfo = {};
userinfo.listId = "userList";
userinfo.userList = null;
userinfo.lastSelectId = -1;
userinfo.pager = '#userpage';
userinfo.editcount = 0;
userinfo.editingIndex = undefined;
userinfo.queryParams =  { };
userinfo.addUser = null;
$(function() {
	 $(window).resize(function(){ //浏览器窗口变更 
		 userinfo.resize();
    	 $("#layout").layout('resize');
    	 userinfo.userList.datagrid('resize');
    	 if(!isOpen){
    	 
    	 }
    	 
     }); 
	userinfo.userList = $("#userList");
	userinfo.addUser = $("#userinfo");
	userinfo.init();
	northEvent();
 }); 
var offetheight = 27;
var isOpen = true;
function northEvent(){
	$("#north").panel({onExpand:function(){
     	var height = $(window).height();
  	    userinfo.userList.datagrid('resize',{height:height-offetheight-1});
  	    userinfo.resize();
  	    isOpen = true;
	} ,onClose:function(){
		 isOpen = false;
	   	 userinfo.resize();
	   	 var height = $(window).height();
	   	 userinfo.userList.datagrid('resize',{height:height-offetheight-1});
	     
    }
    });
	 var height = $(window).height();
	 var north_height = $("#north").height();
	 $("#center").height(height-north_height-offetheight);
	
	 userinfo.resize();
}
userinfo.resize= function(){
	 var north_height = $("#north").height();
	 var height = $(window).height();
	 $("#layout").height(height); 
	 userinfo.userList.datagrid('resize',{height:height-north_height-offetheight});
};
userinfo.init = function( ){
	var columns = [];  
	columns.push({ field: 'id', title: 'id', checkbox:true ,width: 30 ,align : "center" });
	columns.push({ field: 'name', title: '用户名', width: 80 ,align : "center",sortable : true});
	columns.push({ field: 'number', title: '用户编号', width: 80 ,align : "center",sortable : true});
	columns.push({ field: 'oldname', title: '曾用名', width: 80 ,align : "center"});
	//columns.push({ field: 'creatperson', title: '创建人', width: 80 ,align : "center"});
	//columns.push({ field: 'creatdatetime', title: '创建时间', width: 120,align : "center" ,sortable : true});
	columns.push({ field: 'logintimes', title: '登陆次数', width: 65,align : "center" ,sortable : true});
	columns.push({ field: 'logindatetime', title: '最后登陆时间', width: 120,align : "center" ,sortable : true});
	columns.push({ field: 'loginip', title: '最后登陆IP', width: 100,align : "center" });
    columns.push({ field: 'deleteclass', title: '是否已删除', width: 70,align : "center" ,sortable : true
			,formatter: function(value,row,index){
				if (row.deleteclass==true||row.deleteclass=="true"
					||row.deleteclass==1||row.deleteclass=="1"){
					return "已删除";
				} else {
					return "未删除";
				}
			} , editor:{  
	            type:'checkbox',   
	            options:{  
	                on: 'true',  
	                off: 'false'  
	            }  
	        }  
	});
    var validclass = [
        		    {validclassValue:'true',validclassName:'有效'},
        		    {validclassValue:'false',validclassName:'无效'},
              		];
	columns.push({ field: 'validclass', title: '是否有效', width: 80,align : "center" ,sortable : true
		,formatter: function(value,row,index){
			if (row.validclass==true||row.validclass=="true"
				||row.validclass==1||row.validclass=="1"){
				return "有效";
			} else {
				return "无效";
			}
		} 
	    ,   editor:{  
            type:'combobox',  
            panelHeight : "auto", //面板高度
            editable:false, 
            data:validclass,//下拉框中的数据源
            required:true,
            valueField:'validclassValue',  
            textField:'validclassName' 
        }   
	});
	columns.push({ field: 'action', title: '操作', width: 120,align : "center" ,
				   formatter:function(value,row,index){
					  /* var detail = '|<a href="javascript:void(0)" onclick="userinfo.show('+index+')">详情</a>';
					   if (row.editing){  
		                    var s = '<a href="javascript:void(0)" onclick="userinfo.saverow('+index+')">保存</a>';  
		                    var c = '|<a href="javascript:void(0)" onclick="userinfo.cancelrow('+index+')">取消</a>';  
		                    return s+c+ detail;  
		                } else {  
		                    var e = '<a href="javascript:void(0)" onclick="userinfo.editrow('+index+')">编辑</a>';  
		                    var d = '|<a href="javascript:void(0)" onclick="userinfo.deleterow('+index+')">删除</a>';  
		                    return e+d+ detail;  
		                }  */
					   var detail = '<span class="img_view hand" onclick="userinfo.show('+index+')" title="查看"></span>';
					   if (row.editing){  
		                    var s = '<span class="img_save hand" onclick="userinfo.saverow('+index+')" title="保存"></span>';  
		                    var c = '<span class="img_delete hand" onclick="userinfo.deleterow('+index+')" title="删除"></span>';  
		                    return s+c+ detail;  
		                } else {  
		                    var e = '<span class="img_edit hand" onclick="userinfo.editrow('+index+')" title="修改"></span>';  
		                    var d = '<span class="img_delete hand" onclick="userinfo.deleterow('+index+')" title="删除"></span>';  
		                    return e+d+ detail;  
		                } 
				 }
	 });
	var frozenColumns = [];
	var toolbar = []; 
	toolbar.push({ text: '新增', iconCls: 'icon-add', handler: userinfo.addrow});
	//toolbar.push({ text:'保存',iconCls:'icon-save',handler:userinfo.saveAll});
	//toolbar.push({ text:'取消',iconCls:'icon-cancel',handler:userinfo.cancelAll });
	//toolbar.push({ text: '修改', iconCls: 'icon-edit', handler: userinfo.edit});
	toolbar.push({ text: '删除',iconCls: 'icon-remove',handler: userinfo.delAll});
	//toolbar.push({  text: '查找', iconCls: 'icon-search',handler: userinfo.find });
	toolbar.push({ text: '导入',iconCls: 'icon_import',handler: userinfo.delAll});
	toolbar.push({ text: '导出当前页',iconCls: 'icon_export',handler: userinfo.delAll});
	toolbar.push({ text: '导出全部',iconCls: 'icon_export',handler: userinfo.delAll});
	  
	var options = {title: '用户信息',
	        iconCls: 'icon-save',
	        url: 'userinfo_query_json.action',
	        sortName: 'id',
	        sortOrder: 'desc',
	        idField: 'id',
	        loadMsg:"正在努力为您加载数据......",
	        showFooter:true,
	        checkbox:true, 
	        collapsible: true,
	        singleSelect:true,
	        selectOnCheck:false,
	        checkOnSelect:true,
	        rownumbers: true, 
	        pageSize:10,
	        pagination: true,
	        frozenColumns: frozenColumns,
	        columns: [columns],
	        toolbar:toolbar,  
	        queryParams:userinfo.queryParams,
	        onBeforeEdit:userinfo.onBeforeEdit,  
	        onAfterEdit:userinfo.onCancelEdit,  
	        onCancelEdit:userinfo.onCancelEdit,
	        onLoadSuccess:userinfo.onLoadSuccess,
	        onLoadError: userinfo.onLoadError
	        ,onClickCell: userinfo.onClickCell 
	     };
	userinfo.userList.datagrid(options);
	userinfo.addUser.dialog({
		title: '新增用户信息',
		width: 400,
		height: 200, 
		cache: false, 
		modal: true ,
		closed:true,
		buttons: [{
			text:'保存',
			iconCls:'icon-ok',
			handler:userinfo.add
			},{
			text:'取消',
			handler:userinfo.cancel
			}],
		onClose:function(){
			//销毁处理
		}
	 });
};
//点击查找按钮出发事件
function searchFunc() { 
	//$("#searchForm").serialize()
	userinfo.queryParams = $("#searchForm").serializeJson();
    userinfo.userList.datagrid("load",userinfo.queryParams);//将searchForm表单内的元素序列为对象传递到后台
    //这里介绍reload的使用，使用reload时，会默认记住当前页面，当点击查询时，如果我们查到的数据只有三条，我们每页显示10挑数据，当前页码是2，那么我们将无法在当前页面看到我们查询出的结果，只有将页面向前跳转才会看到，但是用load就不会出现这种情况
}

//点击清空按钮出发事件
function clearSearch() {
	userinfo.userList.datagrid("load", {});//重新加载数据，无填写数据，向后台传递值则为空
    $("#searchForm").find("input,select").val("");//找到form表单下的所有input标签并清空
}
userinfo.onClickCell = function(rowIndex, field, value) {
	//alert(value);
	userinfo.beginEditing(rowIndex, field, value);
};

userinfo.beginEditing = function (rowIndex, field, value) {
    if (field != "数量"){
    	return;
    }

    if (rowIndex != userinfo.editingIndex) {
        if (endEditing()) {
            userinfo.userList.datagrid('beginEdit', rowIndex);
            userinfo.editingIndex = rowIndex;

            var ed = userinfo.userList.datagrid('getEditor', { index: rowIndex, field: '数量'});
            $(ed.target).focus().bind('blur', function () {
                endEditing();
            });
        } else {
            userinfo.userList.datagrid('selectRow', userinfo.editingIndex);
        }
    }
};
userinfo.endEditing = function () {
    if (userinfo.editingIndex == undefined) { 
    	return true ;
    }
    if (userinfo.userList.datagrid('validateRow', userinfo.editingIndex)) {
        var ed = userinfo.userList.datagrid('getEditor', { index: userinfo.editingIndex, field: '数量'});
        var number = $(ed.target).numberbox('getValue');
        userinfo.userList.datagrid('getRows')[userinfo.editingIndex]['数量'] = number;
        userinfo.userList.datagrid('endEdit', userinfo.editingIndex);
        userinfo.userList.datagrid('selectRow', userinfo.editingIndex);
        userinfo.editingIndex = undefined;
        return true;
    } else {
        return false;
    }
};
userinfo.onBeforeEdit = function(index,row){  
    row.editing = true;  
    userinfo.userList.datagrid('refreshRow', index);  
    userinfo.editcount ++;
};  
userinfo.onAfterEdit = function(index,row){  
    row.editing = false;  
    userinfo.userList.datagrid('refreshRow', index);  
    userinfo.editcount--;
};  
userinfo.onCancelEdit = function(index,row){  
    row.editing = false;  
    userinfo.userList.datagrid('refreshRow', index);  
    userinfo.editcount--;
};  
userinfo.editrow = function(index){
	userinfo.userList.datagrid('beginEdit', index);
};
userinfo.onLoadSuccess = function(data){

};
userinfo.onLoadError = function(){
	$.messager.alert('警告','加载数据出错！');
};
userinfo.deleterow = function(index){
	$.messager.confirm('确认','是否真的删除?',function(r){
		if (r){
			userinfo.del(index);
		}
	}); 
};

userinfo.saverow = function(index){
	userinfo.userList.datagrid('endEdit', index);
};
userinfo.cancelrow = function(index){
	userinfo.userList.datagrid('cancelEdit', index);
};
userinfo.addrow = function(){
	if (userinfo.editcount > 0){
		$.messager.alert('警告','当前还有'+userinfo.editcount+'记录正在编辑，不能增加记录。');
		return;
	}
	userinfo.addUser.dialog("open");
};  

userinfo.saveAll = function(){
	userinfo.userList.datagrid('acceptChanges');
};
userinfo.cancelAll = function(){
	if (userinfo.editcount > 0){
		$.messager.confirm('确认','当前还有【'+userinfo.editcount+'】条记录正在编辑，是否真的取消所有修改?',function(r){
			if (r){
				userinfo.userList.datagrid('rejectChanges');
			}
		});  
	}else{
		userinfo.userList.datagrid('rejectChanges');
	}
}; 
userinfo.addAjax_action = "userinfo_add_json.action";
var testIndex = 0;
userinfo.addAjax_settting = {
		  type :  "POST",
		  dataType :  "json",
		  data :  {},
		  beforeSend :  function(){
			 
		  },
		  complete :  function(XMLHttpRequest, textStatus){
			  //the request finishes
			 // userinfo.closeaddUser();
			 
		  }, 
		  success :  function(data, textStatus,XMLHttpRequest){
			 // alert(JSON.stringify(userinfo.getRows()));
			  userinfo.closeaddUser(); 
			  if(userinfo.getTotal()>=userinfo.getPageSize()){
				  userinfo.deleteLastRow();
				  userinfo.addOneRow();
			  } 
			  var data = {id:testIndex++,name:"name"+testIndex};
			  userinfo.insertRow(data);
		 },
		 error :  function(XMLHttpRequest, textStatus, errorThrown){
			 userinfo.closeaddUser();
			  
		 }
};
userinfo.closeaddUser= function(){
	 userinfo.addUser.dialog("close");
};
userinfo.add = function(){
	  userinfo.addAjax_settting.data = $("#addUserinfoForm").serialize();
	  $.ajax(userinfo.addAjax_action,userinfo.addAjax_settting);
	  
};
userinfo.cancel = function(){
	userinfo.addUser.dialog("close");
}; 
userinfo.edit = function(){
	
}; 
userinfo.del = function(index){
	userinfo.userList.datagrid('deleteRow', index);
	//需要重新加载
	if(userinfo.getTotal()>userinfo.getPageSize()){
		userinfo.userList.datagrid('reload');
	}
}; 
userinfo.delAll = function(){
	$.messager.confirm('确认','是否真的删除?',function(r){
		if (r){
			userinfo.userList.datagrid('deleteRow', index);
		}
	}); 
}; 
userinfo.show = function(){
	
}; 
userinfo.find = function(){
	
}; 
userinfo.findAll = function(){
	
}; 
 
userinfo.getPage = function(){
	return userinfo.userList.datagrid('options').pageNumber; 
};
userinfo.getPageSize = function(){
	return userinfo.userList.datagrid('options').pageSize; 
};
 
userinfo.getTotal = function(){
	return userinfo.userList.datagrid('getData').total; 
};
userinfo.addOneRow = function(){
	userinfo.userList.datagrid('getData').total++; 
};
 
userinfo.getRows = function(){
	return userinfo.userList.datagrid('getRows'); 
};
userinfo.getData = function(){
	return userinfo.userList.datagrid('getData'); 
};
userinfo.appendRow = function(rowData){
	return userinfo.userList.datagrid('appendRow',rowData); 
};
userinfo.insertRow = function(rowData){
	return userinfo.userList.datagrid('insertRow',{index: 0,	// index start with 0
			row: rowData}); 
};
userinfo.deleteRow = function(index){
	return userinfo.userList.datagrid('deleteRow',index); 
};
userinfo.deleteFirstRow = function(){
	return userinfo.userList.datagrid('deleteRow',0); 
};
userinfo.deleteLastRow = function(){
	var index = userinfo.getTotal()-1;
	if(userinfo.getTotal()>=userinfo.getPageSize()){
		index = userinfo.getPageSize()-1;
	}
	return userinfo.userList.datagrid('deleteRow',index); 
};